﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace Tools
{
    public partial class KillProt : Base
    {
        public KillProt()
        {
            InitializeComponent();
            base.SetDefaultLocation();
        }

        #region 占用端口

        /// <summary>
        /// 占用端口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            TcpListener server = new TcpListener(IPAddress.Any, Convert.ToInt32(txt_port.Text));
            server.Start();
        }
        #endregion

        /// <summary>
        /// 查询端口 并杀掉对应程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            QueryPort(Convert.ToInt32(t_txt_guardport.Text));
        }

        /// <summary>
        /// 查询端口占用程序
        /// </summary>
        /// <param name="port"></param>
        public void QueryPort(int port)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            List<int> listPid = GetPidByPort(p, port);
            if (listPid.Count > 0)
            {
                List<string> list_process = GetProcessNameByPid(p, listPid);
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("占用[" + port + "]端口的进程有:");
                foreach (var item in list_process)
                {
                    sb.Append(item + "\r\n");
                }
                sb.AppendLine("是否要结束这些进程？");
                if (MessageBox.Show(sb.ToString(), "系统提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    PidKill(p, listPid);
                }
            }
            MessageBox.Show("查杀完成");
        }

        private static List<int> GetPidByPort(Process p, int port)
        {
            int result;
            bool b = true;
            p.Start();
            p.StandardInput.WriteLine(string.Format("netstat -ano|find \"{0}\"", port));
            p.StandardInput.WriteLine("exit");
            StreamReader reader = p.StandardOutput;
            string strLine = reader.ReadLine();
            List<int> list_pid = new List<int>();
            while (!reader.EndOfStream)
            {
                strLine = strLine.Trim();
                if (strLine.Length > 0 && ((strLine.Contains("TCP") || strLine.Contains("UDP"))))
                {
                    Regex r = new Regex(@"\s+");
                    string[] strArr = r.Split(strLine);
                    if (strArr.Length >= 4)
                    {
                        b = int.TryParse(strArr[3], out result);
                        if (!b)
                        {
                            b = int.TryParse(strArr[4], out result);
                        }
                        if (b && !list_pid.Contains(result))
                        {
                            if (result > 4)
                            {
                                list_pid.Add(result);
                            }
                        }
                    }
                }
                strLine = reader.ReadLine();
            }
            p.WaitForExit();
            reader.Close();
            p.Close();
            return list_pid;
        }

        private static List<string> GetProcessNameByPid(Process p, List<int> list_pid)
        {
            p.Start();
            List<string> list_process = new List<string>();
            foreach (var pid in list_pid)
            {
                p.StandardInput.WriteLine(string.Format("tasklist |find \"{0}\"", pid));
                p.StandardInput.WriteLine("exit");
                StreamReader reader = p.StandardOutput;//截取输出流
                string strLine = reader.ReadLine();//每次读取一行

                while (!reader.EndOfStream)
                {
                    strLine = strLine.Trim();
                    if (strLine.Length > 0 && ((strLine.Contains(".exe"))))
                    {
                        Regex r = new Regex(@"\s+");
                        string[] strArr = r.Split(strLine);
                        if (strArr.Length > 0)
                        {
                            list_process.Add(strArr[0]);
                        }
                    }
                    strLine = reader.ReadLine();
                }
                p.WaitForExit();
                reader.Close();
            }
            p.Close();

            return list_process;
        }

        private static void PidKill(Process p, List<int> list_pid)
        {
            p.Start();
            foreach (var item in list_pid)
            {
                p.StandardInput.WriteLine("taskkill /pid " + item + " /f");
                p.StandardInput.WriteLine("exit");
            }
            p.Close();
        }
    }
}
